package com.loong.android.sqlite;

import android.text.TextUtils;

import com.loong.android.sqlite.data.EntityFieldData;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class CommonEntityDao {

    private final static String TAG = "CommonEntityDao";

    /**
     * 获取猎码表实体中的字段
     * @param lcEntityClass 猎码表实体类
     */
    public static List<EntityFieldData> handleEntityKeys(Class lcEntityClass) {
        List<EntityFieldData> entityFieldDataList = new ArrayList<>();
        if (lcEntityClass == null) return entityFieldDataList;
        Field[] fieldList = lcEntityClass.getDeclaredFields();
        if (fieldList == null || fieldList.length <= 0) return entityFieldDataList;
        Object obj = null;
        try {
            obj = lcEntityClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (Field field : fieldList) {
            if (field == null) continue;
            field.setAccessible(true);
            String name = field.getName();
            if (TextUtils.isEmpty(name) || name.length() <= 3) continue;
            if (!name.substring(0, 3).equalsIgnoreCase("db_")) continue;
            EntityFieldData data = new EntityFieldData();
            data.setName(name);
            if (data.getName().equals(CommonEntity.ID_KEY)) {
                data.setColumnName(CommonEntity.ID_COLUMN_KEY);
            }else {
                data.setColumnName(data.getName());
            }
            data.setType(field.getType().getSimpleName());
            try {
                data.setDefVal(field.get(obj));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            entityFieldDataList.add(data);
        }
        return entityFieldDataList;
    }

    public static String getSqliteColumnTypeByStr(String columnType) {
        if (TextUtils.isEmpty(columnType)) return "TEXT";
        if (columnType.equalsIgnoreCase("string")) {
            return "TEXT";
        }else if (columnType.equalsIgnoreCase("boolean")) {
            return "INTEGER";
        }else if (columnType.equalsIgnoreCase("long")) {
            return "INTEGER";
        }else if (columnType.equalsIgnoreCase("integer")) {
            return "INTEGER";
        }else if (columnType.equalsIgnoreCase("short")) {
            return "INTEGER";
        }else if (columnType.equalsIgnoreCase("float")) {
            return "REAL";
        }else if (columnType.equalsIgnoreCase("double")) {
            return "REAL";
        }
        return "TEXT";
    }
    
}
